<?php
/**
 * Created by PhpStorm.
 * User: jh
 * Date: 2018-03-20
 * Time: 17:09
 */

namespace frontend\controllers;

use common\helpers\TStringHelper;
use common\models\ExhibitionCategory;
use common\models\User;
use common\models\UserCompany;
use common\models\UserFollow;
use common\services\ExhibitionCategoryServices;
use common\services\ExhibitionServices;
use common\services\UserCompanyServices;
use common\services\UserMessageServices;
use common\services\UserServices;
use frontend\base\BaseFrontController;
use frontend\models\ChangePasswordForm;
use Yii;
use yii\base\InvalidParamException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use frontend\models\SmsLog;
use yii\web\BadRequestHttpException;
use yii\web\Response;

class MemberController extends BaseFrontController
{

    public $sendError;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                //'only' => ['login', 'logout', 'register'],
                'rules' => [
                    [
                        'actions' => ['register', 'login', 'sendcaptcha'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        //'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $userId = Yii::$app->user->id;
        //用户信息
        $user = User::findOne($userId);
        //消息
        $messageService = new UserMessageServices();
        $messageRemind = $messageService->getMessageRemindByUserId($userId);

        //展会浏览历史
        $exhibitionService = new ExhibitionServices();
        $history = $exhibitionService->getUserHistoryByUserId($userId);
        //我关注的展会
        $myFollow = $exhibitionService->getMyFollowList($userId, UserFollow::USER_FOLLOW_TYPE_EXHIBITION);
        //展会推荐
        $recommend = $exhibitionService->getUserInterestByUserId($userId, 4);
        $userService = new UserServices();
        $safety_grade = $userService->getAccountSafetyGrade($user);

        return $this->render('index', [
            'user' => $user,
            'messageRemind' => $messageRemind,
            'history' => $history,
            'myFollow' => $myFollow,
            'recommend' => $recommend,
            'safety_grade' => $safety_grade,
        ]);
    }

    /**
     * 退出
     * @return Response
     */
    public function actionLogout(){
        Yii::$app->user->logout(null);

        return $this->goHome();
    }

    /**
     * 登录
     * */
    public function actionLogin(){
        //已经登录
        if (!Yii::$app->user->isGuest) {
            $url = Yii::$app->urlManager->createUrl(['member/index']);
            header("Location:".$url);
            exit;
        }

        $data = Yii::$app->request->post();
        if (Yii::$app->request->isPost) {
            if (empty($data['username'])) {
                Yii::$app->getSession()->setFlash('error', '用户名不能为空');
            }else {
                $userObj = User::findByUserinfo($data['username']);
                if (empty($userObj)) {
                    Yii::$app->getSession()->setFlash('error', '该用户不存在');
                }else {
                    if ($userObj->validatePassword($data['password']) === false) {
                        Yii::$app->getSession()->setFlash('error', '密码错误');
                    }else {
                        if ($userObj->status != User::STATUS_FLAG_NORMAL) {
                            Yii::$app->getSession()->setFlash('error', '用户被禁用');
                        }else {
                            Yii::$app->user->login($userObj);
                            //跳转到上次记录的页面（登录之前的页面）
                            $preview = Url::previous('preview');
                            if (empty($preview)) {
                                header("Location:" . Yii::$app->urlManager->createUrl(['member/index']));
                                exit;
                            }
                            header("Location:{$preview}");
                            exit;
                        }
                    }
                }
            }
        }
        $this->layout = 'main-min';
        return $this->render('login', [
            'data' => $data,
        ]);
    }

    /**
     * 注册
     * */
    public function actionRegister(){
        //已经登录
        if (!Yii::$app->user->isGuest) {
            $url = Yii::$app->urlManager->createUrl(['member/index']);
            header("Location:".$url);
            exit;
        }
        $data = Yii::$app->request->post();
        if (Yii::$app->request->isPost) {
            $memberModel = new User();
            $result = $memberModel->register($data);
            if ($result['code'] == 0) {
                //Yii::$app->getSession()->setFlash('success', '注册成功,请登录');
                //$this->redirect(Yii::$app->urlManager->createUrl(['member/login']));
                $model = User::findOne($result['data']);
                Yii::$app->user->login($model);
                $this->redirect(Yii::$app->urlManager->createUrl(['member/register-success']));
                exit;
            }else{
                Yii::$app->getSession()->setFlash('error', $result['msg']);
            }
        }
        $this->layout = 'main-min';
        return $this->render('register', [
            'data' => $data,
        ]);
    }

    /**
     * 注册成功
     * @return string
     */
    public function actionRegisterSuccess(){
        $this->layout = 'main-min';
        $userId = Yii::$app->user->id;
        $userCompany = UserCompany::findOne(['user_id' => $userId]);
        if (!empty($userCompany)) {
            if ($userCompany->type == UserCompany::COMPANY_TYPE_Z) {
                $url = Yii::$app->urlManager->createUrl(['/member/zhubanfang']);
            }elseif ($userCompany->type == UserCompany::COMPANY_TYPE_C) {
                $url = Yii::$app->urlManager->createUrl(['/member/canzhanshang']);
            }elseif ($userCompany->type == UserCompany::COMPANY_TYPE_F) {
                $url = Yii::$app->urlManager->createUrl(['/member/fuwushang']);
            }
            Yii::$app->response->redirect($url);
            exit;
        }
        return $this->render('register-success', [

        ]);
    }


    /**
     * 发送短信验证码
     */
    public function actionSendcaptcha()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $mobile = Yii::$app->request->post('tel');
        //生成6位随机数的验证码
        $code = rand(100000,999999);
        $sms = Yii::$app->system->getValueByCode('sms');
        $sms = explode('|', $sms);
        //调用sendSms发送短信
        $result = $this->sendmsg(
            $sms[0],
            $mobile,
            $sms[1],
            [
                'code' => $code,
                'time' => $sms[2]
            ]);
        //Yii::$app->session->set('reg_'.$mobile, 123456);

        if ($result == false) {
            return ['code' => 1, 'data' => [], 'message' => $this->sendError];
        }

        //将验证码写入session中保存
        Yii::$app->session->set('reg_'.$mobile, $code);
        return ['code' => 0, 'data' => [], 'message' => '发送成功'];
    }


    /**
     * @param string $signname
     * @param $mobile
     * @param $templatecode
     * @param array $data
     * @return bool
     * 发送短信方法
     */
    public function sendmsg($signname="中国会展网", $mobile, $templatecode,array $data, $outId = null)
    {
        $pregMobile = '/^1\d{10}$/';
        if (!preg_match($pregMobile, $mobile)) {
            $this->sendError = "电话号码格式错误";
            return false;
        }
        //防刷判断
        /**
         * 【在相同业务中】两次【发送成功】时间必须【大于2分钟】
         */
        if (SmsLog::find()->where([
            'AND',
            [
                'mobile'=> $mobile,
                'template_code'=> json_encode($templatecode),
                'status'=> 1,
            ],
            ['<', 'create_time', time()-120]])->exists()
        ) {
            $this->sendError = "两次发送时间必须大于2分钟";
            return false;
        }

        //发送短信
        $result =  Yii::$app->aliyun->sendSms(
            $signname, // 短信签名
            $templatecode, // 短信模板编号
            $mobile, // 短信接收者
            /*Array(  // 短信模板中字段的值
                "code"=>"12345",
                "product"=>"dsd"
            ),*/
            $data,// 短信模板中字段的值
            $outId
        );

        $result = json_decode($result, true);

        //将发送信息写入日志
        $smsLogModel = new SmsLog();
        $smsLogModel->mobile = $mobile;
        $smsLogModel->code = $data['code'];
        $smsLogModel->template_code = json_encode($templatecode);
        $smsLogModel->sign_name = $signname;
        $smsLogModel->create_time = time();

        //判断发送结果
        if ($result['code'] != 'OK') {
            $smsLogModel->status = 0;
            $this->sendError = $result['message'];
            $smsLogModel->save();
            return false;
        }

        $smsLogModel->status = 1;
        $smsLogModel->save();
        return true;
    }

    /**
     * 我的关注
     * @return string
     */
    public function actionFollow(){
        $userId = Yii::$app->user->getId();
        $exhibitionService = new ExhibitionServices();
        $params = array(
            'user_id' => $userId,
            'defaultPageSize' => 3,
        );
        $data = $exhibitionService->searchUserFollow($params);
        //展会推荐
        $recommend = $exhibitionService->getUserInterestByUserId($userId, 9);

        return $this->render('follow', [
            'data' => $data,
            'recommend' => $recommend,
        ]);
    }

    /**
     * 我的点评
     * @return string
     */
    public function actionComments(){
        $userId = Yii::$app->user->getId();
        $exhibitionService = new ExhibitionServices();
        //展会推荐
        $recommend = $exhibitionService->getUserInterestByUserId($userId, 9);

        return $this->render('comments', [
            'recommend' => $recommend,
        ]);
    }

    /**
     * 浏览历史
     * @return string
     */
    public function actionHistory(){
        $userId = Yii::$app->user->getId();
        $exhibitionService = new ExhibitionServices();
        //展会推荐
        $recommend = $exhibitionService->getUserInterestByUserId($userId, 9);
        $params = array(
            'user_id' => $userId,
            'defaultPageSize' => 6,
        );
        $history = $exhibitionService->searchUserHistory($params);

        return $this->render('history', [
            'recommend' => $recommend,
            'data' => $history,
        ]);
    }

    /**
     * 用户基本资料
     * @return string
     */
    public function actionInfo(){
        $userId = Yii::$app->user->getId();
        $model = User::findOne($userId);

        if (Yii::$app->request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $data = Yii::$app->request->post();
            $userService = new UserServices();
            $result = $userService->updateBasic($data, $model);
            return $result;
        }
        $userCompany = UserCompany::findOne(['user_id' => $userId]);

        //行业分类
        $categoryService = new ExhibitionCategoryServices();
        $category = $categoryService->getIndexCategory();
        $exhibitionCategory = array();
        if (!empty($category)) {
            $exhibitionCategory = ArrayHelper::map($category, 'id', 'name');
        }

        return $this->render('info', [
            'model' => $model,
            'industry' => $category,
            'userCompany' => $userCompany,
            'exhibitionCategory' => $exhibitionCategory,
        ]);
    }

    /**
     * 保存公司信息
     */
    public function actionSaveCompany(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $userId = Yii::$app->user->getId();
        $model = UserCompany::findOne(['user_id' => $userId]);
        if (empty($model)) {
            return ['code' => -1, 'data' => [], 'msg' => '公司信息不存在'];
        }
        if ($model->load(Yii::$app->request->post())) {
            if (!empty($model->category_id)) {
                $categoryName = ExhibitionCategory::getExhibitionCategoryName($model->category_id);
                $model->category = $categoryName;
            }
            $model->save();
            return ['code' => 0, 'data' => [], 'msg' => 'ok'];
        }else{
            return ['code' => -1, 'data' => [], 'msg' => '保存失败'];
        }
    }

    /**
     * 修改密码
     * @return string
     */
    public function actionChangepwd(){

        try {
            $model = new ChangePasswordForm();
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        $is_ok = false;
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if (TStringHelper::CheckPasswordStrength($model->password_new) < 2) {
                $model->error_message = Yii::t('frontend', 'password_strength_less');
                return $this->render('changepwd', [
                    'model' => $model,
                    'is_ok' => $is_ok,
                ]);
            }
            if ($model->validate()) {
                $result = $model->resetPassword();
                if ($result['result'] == 'success') {
                    /*$url = Yii::$app->urlManager->createUrl(['member/index']);
                    return $this->goBack($url);*/
                    $model = new ChangePasswordForm();
                    $model->error_message = Yii::t('frontend', 'modify_success');
                    $is_ok = true;
                }else{
                    $model->error_message = $result['message'];
                }
                return $this->render('changepwd', [
                    'model' => $model,
                    'is_ok' => $is_ok,
                ]);
            } else {
                $model->error_message = Yii::t('frontend', 'change_password_error');
                return $this->render('changepwd', [
                    'model' => $model,
                    'is_ok' => $is_ok,
                ]);
            }
        }

        return $this->render('changepwd', [
            'model' => $model,
            'is_ok' => $is_ok,
        ]);
    }

    /**
     * 主办方
     * @return string
     */
    public function actionZhubanfang(){
        $userId = Yii::$app->user->getId();
        $companyService = new UserCompanyServices();
        $model = $companyService->getUserCompanyInfo($userId, UserCompany::COMPANY_TYPE_Z);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->status = 3;//审核中
        }
        $reset = Yii::$app->request->get('reset');
        if (isset($reset) && $model->status == 2) {
            $model->status = 0;//重新提交申请
            $model->update();
        }

        return $this->render('zhubanfang', [
            'model' => $model,
        ]);
    }

    /* *
     * 参展商
     */
    public function actionCanzhanshang(){
        $userId = Yii::$app->user->getId();
        $companyService = new UserCompanyServices();
        $model = $companyService->getUserCompanyInfo($userId, UserCompany::COMPANY_TYPE_C);
        $user = User::findOne($userId);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (!empty($model->category_id)) {
                $categoryName = ExhibitionCategory::getExhibitionCategoryName($model->category_id);
                $model = UserCompany::findOne($model->id);
                $model->category = $categoryName;
                $model->update();
            }
            //更新用户信息
            $user->realname = Yii::$app->request->post('realname');
            $user->email = Yii::$app->request->post('email');
            $user->update();
        }
        //行业分类
        $categoryService = new ExhibitionCategoryServices();
        $category = $categoryService->getIndexCategory();
        if (!empty($category)) {
            $category = ArrayHelper::map($category, 'id', 'name');
        }

        $title = Yii::t('frontend', 'canzhanshang');
        return $this->render('canzhanshang', [
            'model' => $model,
            'user' => $user,
            'category' => $category,
            'title' => $title,
        ]);
    }

    /**
     * 服务商
     * @return string
     */
    public function actionFuwushang(){
        $userId = Yii::$app->user->getId();
        $companyService = new UserCompanyServices();
        $model = $companyService->getUserCompanyInfo($userId, UserCompany::COMPANY_TYPE_F);
        $user = User::findOne($userId);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (!empty($model->category_id)) {
                $categoryName = ExhibitionCategory::getExhibitionCategoryName($model->category_id);
                $model = UserCompany::findOne($model->id);
                $model->category = $categoryName;
                $model->update();
            }
            //更新用户信息
            $user->realname = Yii::$app->request->post('realname');
            $user->email = Yii::$app->request->post('email');
            $user->update();
        }
        //行业分类
        $categoryService = new ExhibitionCategoryServices();
        $category = $categoryService->getIndexCategory();
        if (!empty($category)) {
            $category = ArrayHelper::map($category, 'id', 'name');
        }

        $title = Yii::t('frontend', 'fuwushang');
        return $this->render('canzhanshang', [
            'model' => $model,
            'user' => $user,
            'category' => $category,
            'title' => $title,
        ]);
    }

}